/**
 * 电影数据状态管理
 * 使用Pinia进行状态管理
 */

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { movieAPI } from '../api'
import { mockMovies } from '../utils/mockData'
import type { Movie } from '../utils/http'

export const useMovieStore = defineStore('movie', () => {
  // 状态
  const movies = ref<Movie[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)
  const currentPage = ref(1)
  const pageSize = ref(20)
  const total = ref(0)

  // 计算属性
  const hasMore = computed(() => movies.value.length < total.value)
  const isEmpty = computed(() => movies.value.length === 0 && !loading.value)

  /**
   * 获取热门电影
   */
  const fetchHotMovies = async (reset: boolean = false) => {
    if (reset) {
      currentPage.value = 1
      movies.value = []
    }

    loading.value = true
    error.value = null

    try {
      const start = (currentPage.value - 1) * pageSize.value
      
      // 尝试调用真实API
        let response:any
        try {
          response = await movieAPI.getHotMovies({
            category: '热门',
            type: '全部',
            limit: pageSize.value,
            start: start
          })
        } catch (apiError) {
          console.warn('API调用失败，使用模拟数据:', apiError)
          // 使用模拟数据作为后备
          const mockData = mockMovies.slice(start, start + pageSize.value)
          response = { data: mockData, total: mockData.length + 100 }
          error.value = '使用演示数据（API暂时不可用）'
        }
      
      // 处理响应格式 - 支持AxiosResponse和直接数据
      let data: any
      let items: any[]
      if (response && typeof response === 'object') {
        if ('data' in response) {
          // AxiosResponse格式
          data = response.data
        } else {
          // 直接数据格式
          data = response
        }
        items = data.subjects || data.list || (Array.isArray(data) ? data : [])
      } else {
        items = []
        data = { total: 0 }
      }
      
      if (Array.isArray(items)) {
        if (reset) {
          movies.value = items
        } else {
          movies.value.push(...items)
        }
        total.value = data.total || items.length
      } else {
        console.warn('Unexpected API response format:', response)
        // 使用模拟数据作为最后备选
        const mockData = mockMovies.slice(start, start + pageSize.value)
        movies.value = mockData
        total.value = mockData.length + 100
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '获取电影数据失败'
      console.error('Failed to fetch hot movies:', err)
    } finally {
      loading.value = false
    }
  }

  /**
   * 加载更多电影
   */
  const loadMore = async () => {
    if (!hasMore.value || loading.value) return
    
    currentPage.value++
    await fetchHotMovies()
  }

  /**
   * 搜索电影
   */
  const search = async (query: string) => {
    loading.value = true
    error.value = null

    try {
      const response = await movieAPI.searchMovies(query, {
        limit: pageSize.value,
        start: 0
      })
      
      // 处理响应格式 - 支持AxiosResponse和直接数据
      let data: any
      let items: any[]
      
      if (response && typeof response === 'object') {
        if ('data' in response) {
          data = response.data
        } else {
          data = response
        }
        items = data.subjects || data.data || (Array.isArray(data) ? data : [])
      } else {
        items = []
        data = { total: 0 }
      }
      
      if (Array.isArray(items)) {
        movies.value = items
        total.value = data.total || items.length
      } else {
        movies.value = []
        total.value = 0
      }
    } catch (err) {
      error.value = err instanceof Error ? err.message : '搜索失败'
      console.error('Failed to search movies:', err)
    } finally {
      loading.value = false
    }
  }

  /**
   * 重置状态
   */
  const reset = () => {
    movies.value = []
    loading.value = false
    error.value = null
    currentPage.value = 1
    total.value = 0
  }

  return {
    // 状态
    movies,
    loading,
    error,
    currentPage,
    pageSize,
    total,
    
    // 计算属性
    hasMore,
    isEmpty,
    
    // 方法
    fetchHotMovies,
    loadMore,
    search,
    reset
  }
})